/**
 * Copyright 2024 Inc.
 **/
package com.myz.springboot2.xml.utils;

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author maoyz0621 on 2024/10/22
 * @version v1.0
 */
public class BeanCopyUtils {

    public static <T> T deepCopy(T object) {
        if (object == null) {
            return null;
        }

        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            bis = new ByteArrayInputStream(baos.toByteArray());
            ois = new ObjectInputStream(bis);
            return (T) ois.readObject();
        } catch (ClassNotFoundException | IOException e) {
            throw new RuntimeException("Fail to deep copy", e);
        } finally {
            IOUtils.closeQuietly(baos);
            IOUtils.closeQuietly(oos);
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(ois);
        }
    }
}